package com.vm.action.driverInfo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Preparable;
import com.vm.action.ActionSuper;
import com.vm.common.Page;
import com.vm.dao.driverinfo.DriverInfoDao;
import com.vm.dao.phoneInfo.IPhoneInfoDao;
import com.vm.entity.DriverInfo;
import com.vm.entity.PhoneInfo;
import com.vm.log4j.CustomizeLog4j;
import com.vm.service.DriverInfoService;
import com.vm.util.SQLUtils;
import com.vm.util.ZipUtils;

public class DriverInfoAction extends ActionSuper implements Preparable {

	private static Logger log = CustomizeLog4j
			.getLogger(DriverInfoAction.class);
	private Page<DriverInfo> page;
	private DriverInfo driverInfo;

	
	private DriverInfoDao driverInfoDao;

	private IPhoneInfoDao phoneInfoDao;

    //品牌
	private String brand;

	private String pageLinkList;

	private File driverFile;
	
	private File driverUpdateFile;
	


	private Integer cbSystemId;
	
	private Integer setupStyleId;
	
	private Integer driverMId;

	// 驱动文件名称
	private String driverFileFileName;

	private Map<String, String> phoneBrand;

	
	private String[] mobileIds = null;

	private DriverInfoService driverInfoService;

	// 适配驱动机型
	private String setupName;

	@Override
	public void prepare() throws Exception {
		// 载入适配驱动机型
		String sql = SQLUtils.getDriverInfoSQL();
		phoneBrand = driverInfoDao.getSelectPoMap2(sql);

	}

	public String list() {
		this.page = this.driverInfoDao.page(this.PAGE_ROW_SIZE, super
				.getPageNumber());
		this.pageLinkList = super.getSplitPageLink(
				"/driver/driverInfoAction_list.do?", this.page);
		return SUCCESS;
	}

	public String add() throws Exception {
		return SUCCESS;
	}

	public String save() throws Exception {
		String[] msgArg = new String[] { "driverInfoAction_list.do" };
		String msg = null;
		try {
			if (this.driverFile == null) {
				log.error("--未能得到上传zip--");
				msg = super.getResourceMessage("未上传文件", msgArg);
				super.setShowMessage(msg);
				return super.SHOW_MESSAGE_RESULT;
			}

			Boolean isCheck = ZipUtils.ZipFile(driverFile);
			if (!isCheck) {
				log.error("--上传文件不符合zip 格式，请重新上传--");
				msg = super.getResourceMessage("上传文件不符合zip 格式，请重新上传", msgArg);
				super.setShowMessage(msg);
				return super.SHOW_MESSAGE_RESULT;

			}
			if (this.getFileSize(this.driverFile) > 31457280) {
				log.error("--上传文件大小不正确，请重新上传--");
				msg = super.getResourceMessage("上传文件大小不正确，请重新上传", msgArg);
				super.setShowMessage(msg);
				return super.SHOW_MESSAGE_RESULT;

			}

			// 保存驱动库
			String path = "";

			path = this.fileUpdate(this.driverFile, driverFileFileName);
			driverInfo.setPath(path);
			driverInfo.setUserId("1");
			driverInfo.setUserName("admin");
			driverInfo.setName(this.driverFileFileName);
			driverInfo.setCreateDate(new Timestamp(new Date().getTime()));
			
			Integer driverId =(Integer)driverInfoDao.save(driverInfo);
			DriverInfo driverTemp = new DriverInfo();
			driverTemp.setId(driverId);
			if(mobileIds != null && mobileIds.length > 0)
		    {
				for(int i = 0;i < mobileIds.length;i++)
				{
				    String mobileId = mobileIds[i];
				    PhoneInfo phoneInfo = phoneInfoDao.findById(Integer.valueOf(mobileId));
				    phoneInfo.setDriverInfo(driverTemp);
				    phoneInfoDao.update(phoneInfo);
				}
			
		    }
			msg = super
					.getResourceMessage("insert_driverInfo_success", msgArg);
		} catch (Exception e) {
			log.error("driverInfoAction save driverInfo error  ", e);
			msg = super.getResourceMessage("insert_driverInfo_err", msgArg);
		}
		super.setShowMessage(msg);
		return super.SHOW_MESSAGE_RESULT;
	}

	public String edit() {
		driverInfo = driverInfoDao.findById(this.driverInfo.getId());
		return SUCCESS;
	}

	public String update() throws Exception {
		String[] msgArg = new String[] { "driverInfoAction_list.do"};
		String msg = null;
		try {
			if(driverInfo.getId() != null ){
		       System.out.println(driverInfo.getName());
			}
			// 判断文件大小，文件大小不能大于10M
			if(driverFile != null)
			{
					Boolean isCheck = ZipUtils.ZipFile(driverFile);
					if(!isCheck){
						log.error("--上传文件不符合zip 格式，请重新上传--");
						msg = super.getResourceMessage("上传文件不符合zip 格式，请重新上传", msgArg);
						super.setShowMessage(msg);
						return super.SHOW_MESSAGE_RESULT;
						
					}
				    if(this.getFileSize(this.driverFile) > 31457280)
				    {
				    	log.error("--上传文件大小不正确，请重新上传--");
						msg = super.getResourceMessage("上传文件大小不正确，请重新上传", msgArg);
						super.setShowMessage(msg);
						return super.SHOW_MESSAGE_RESULT;
					
				    }
				  
				 // 保存驱动库
					String path ="";
					
				    path = this.fileUpdate(this.driverFile,driverFileFileName);
                    
				    driverInfo.setPath(path);
				    driverInfo.setName(this.driverFileFileName);
		         }
					driverInfo.setUserId("1");
					driverInfo.setUserName("admin");
					driverInfo.setCreateDate(new Timestamp(new Date().getTime()));
					driverInfoDao.update(driverInfo);
					DriverInfo driverTemp = new DriverInfo();
					driverTemp.setId(driverInfo.getId());
					
					if(mobileIds != null && mobileIds.length > 0)
				    {
			
						for(int i = 0;i < mobileIds.length;i++)
						{
						    String mobileId = mobileIds[i];
						    PhoneInfo phoneInfo = phoneInfoDao.findById(Integer.valueOf(mobileId));
					        
						    phoneInfo.setDriverInfo(driverTemp);
						    phoneInfoDao.update(phoneInfo);
						}
					
				    }
					msg = super.getResourceMessage("update_driverInfo_success", msgArg);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("driverInfoAction save driverInfo error  ", e);
			msg = super.getResourceMessage("update_driverInfo_err", msgArg);
		}
		super.setShowMessage(msg);
		return super.SHOW_MESSAGE_RESULT;

	}

	public String delete() {
		String[] msgArg = new String[] { "driverInfoAction_list.do" };
		String msg = null;
		try {
			// 删除驱动
			if(this.driverInfo.getId() == null || this.driverInfo.getId() == 0)
			{
				log.error("--删除失败！");
				msg = super.getResourceMessage("删除失败！", msgArg);
				super.setShowMessage(msg);
				return super.SHOW_MESSAGE_RESULT;

			}
			driverInfoDao.deleteById(this.driverInfo.getId());
			msg = super.getResourceMessage("delete_driverInfo_success", msgArg);
			
		} catch (Exception e) {
			log.error("删除失败！请先将适配 机型修改为空再尝试删除  ", e);
			msg = super.getResourceMessage("delete_driverInfo_err", msgArg);
		}
		super.setShowMessage(msg);
		return super.SHOW_MESSAGE_RESULT;
	}

	public String getSelectMobile() throws IOException {
		StringBuffer sb = new StringBuffer();
		sb.append(" from  PhoneInfo pi ");
		Object[] params = new Object[1];
		List<PhoneInfo> phoneInfoList =  null;
		if(brand != null && !"".equals(brand)){
			sb.append(" where pi.piPp = ? ");
			params[0] = brand;
			phoneInfoList =phoneInfoDao.findByHql(sb.toString(), params);
		}else{
			phoneInfoList = phoneInfoDao.findAll();
		}
		String  str="";
		
		if(phoneInfoList != null && phoneInfoList.size() > 0){
			 str ="{\"result\":[";
			for(int i = 0;i<phoneInfoList.size();i++){
			         PhoneInfo phoneInfo = phoneInfoList.get(i);
			   	str+="{\"id\":"+phoneInfo.getPiId()+","+"\"jx\":"+phoneInfo.getPiJx()+"}";
			   	if(i < (phoneInfoList.size() -1)){
			   		str += ",";
			   	}
			}
			str+="]}";
		}
		//暂用此方式
		 HttpServletResponse response = ServletActionContext.getResponse();
		 response.setHeader("Cache-Control", "no-cache");
	     response.setCharacterEncoding("UTF-8");
	     PrintWriter out = response.getWriter();
	     out.write(str);
	     out.close();
	     return null;
	}
	 /**
     * json格式
     * 
     * @param json
     * @throws IOException
     */
    public  void objectJson(JSONObject json) throws IOException
    {
    	

        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("application/json") ;
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        System.out.println(json.toString());
        out.write(json.toString());
        out.close();
    }
	/**
	 *得到文件大小
	 * 
	 * @throws Exception
	 **/
	public Long getFileSize(File file) throws Exception {
		FileInputStream fileInput = null;
		Long l = 0L;
		try {
			fileInput = new FileInputStream(file);
			l = (long) fileInput.available();

		} catch (FileNotFoundException e) {
			throw new Exception("文件没有找到", e);
		} catch (IOException e) {
			throw new Exception("文件操作失败", e);
		}
		return l;
	}
	public String fileUpdate(File driverFile, String fileName) throws Exception {
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
		String path = ServletActionContext.getRequest().getRealPath("/")+File.separator+"upload";
		Date date = new Date(System.currentTimeMillis());
		File hereFile = new File(path + File.separator + sdf2.format(date));
		if (!hereFile.exists()) {
			hereFile.mkdirs();
		}

		path = hereFile.toString() + File.separator + fileName;
		if (driverFile != null) {
			FileOutputStream fos = new FileOutputStream(path);
			FileInputStream fis = new FileInputStream(driverFile);

			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}
			fis.close();
			fos.close();
		}

		String downLoadPath =ServletActionContext.getRequest().getRealPath("/")+File.separator + "upload";
		downLoadPath = downLoadPath + File.separator + sdf2.format(date) + File.separator + fileName;
		return downLoadPath;
	}
	
	
	public void setPage(Page<DriverInfo> page) {
		this.page = page;
	}

	public DriverInfo getDriverInfo() {
		return driverInfo;
	}

	public void setDriverInfo(DriverInfo driverInfo) {
		this.driverInfo = driverInfo;
	}

	public String getPageLinkList() {
		return pageLinkList;
	}

	public void setPageLinkList(String pageLinkList) {
		this.pageLinkList = pageLinkList;
	}

	public Page<DriverInfo> getPage() {
		return page;
	}

	public File getDriverFile() {
		return driverFile;
	}

	public void setDriverFile(File driverFile) {
		this.driverFile = driverFile;
	}

	public DriverInfoDao getDriverInfoDao() {
		return driverInfoDao;
	}

	public void setDriverInfoDao(DriverInfoDao driverInfoDao) {
		this.driverInfoDao = driverInfoDao;
	}

	
	public String getDriverFileFileName() {
		return driverFileFileName;
	}

	public void setDriverFileFileName(String driverFileFileName) {
		this.driverFileFileName = driverFileFileName;
	}

	public String getSetupName() {
		return setupName;
	}

	public void setSetupName(String setupName) {
		this.setupName = setupName;
	}

	/**
	 * @return the mobileIds
	 */
	public String[] getMobileIds() {
		return mobileIds;
	}

	/**
	 * @param mobileIds
	 *            the mobileIds to set
	 */
	public void setMobileIds(String[] mobileIds) {
		this.mobileIds = mobileIds;
	}

	
	
	public IPhoneInfoDao getPhoneInfoDao() {
		return phoneInfoDao;
	}

	public void setPhoneInfoDao(IPhoneInfoDao phoneInfoDao) {
		this.phoneInfoDao = phoneInfoDao;
	}

	public DriverInfoService getDriverInfoService() {
		return driverInfoService;
	}

	public void setDriverInfoService(DriverInfoService driverInfoService) {
		this.driverInfoService = driverInfoService;
	}

	public Integer getCbSystemId() {
		return cbSystemId;
	}

	public void setCbSystemId(Integer cbSystemId) {
		this.cbSystemId = cbSystemId;
	}

	public Integer getSetupStyleId() {
		return setupStyleId;
	}

	public void setSetupStyleId(Integer setupStyleId) {
		this.setupStyleId = setupStyleId;
	}

	public Integer getDriverMId() {
		return driverMId;
	}

	public void setDriverMId(Integer driverMId) {
		this.driverMId = driverMId;
	}
	
	public Map<String, String> getPhoneBrand() {
		return phoneBrand;
	}

	public void setPhoneBrand(Map<String, String> phoneBrand) {
		this.phoneBrand = phoneBrand;
	}
	public String getBrand() {
		return brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}
	
	public File getDriverUpdateFile() {
		return driverUpdateFile;
	}

	public void setDriverUpdateFile(File driverUpdateFile) {
		this.driverUpdateFile = driverUpdateFile;
	}


}
